<!--  -->
<template>
  <div class="">
    <el-tree
      :data="menus"
      :props="defaultProps"
      show-checkbox
      node-key="catId"
      :expand-on-click-node="false"
      :default-expanded-keys="expandKey"
      draggable
      :allow-drop="allowDrop"
      @node-drop="handleDrop"

    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">添加</el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">修改</el-button>
          <el-button v-if="node.childNodes.length === 0" type="text" size="mini"
                     @click="() => remove(node, data)">删除</el-button>
        </span>
        </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category" ref="category" :rules="rules">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="category.name" style="width: 85%"></el-input>
        </el-form-item>
        <el-form-item label=图标地址 prop="icon">
          <el-input v-model="category.icon" style="width: 85%"></el-input>
        </el-form-item>
        <el-form-item label=计量单位 prop="productUnit">
          <el-input v-model="category.productUnit" style="width: 85%"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

// import log from '../sys/log'

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},

  data () {
    return {
      updateNodes: [],
      menus: [],
      dialogVisible: false,
      maxLevel: 0,
      dialogType: '',
      title: '',
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productCount: 0,
        icon: '',
        productUnit: '',
        catId: null
      },
      expandKey: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        name: [
          {required: true, message: '请输入菜单名称', trigger: 'blur'}
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    getMenuList () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        console.log('获取到了数据....', data.data)
        this.menus = data.data
      })
    },
    append (data) {
      this.dialogType = 'add'
      this.title = '添加分类'
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.parentCid = data.catId
      this.category.showStatus = 1
      this.category.sort = 0
      this.category.name = null
      this.category.icon = null
      this.category.productUnit = null
      this.category.catId = null
      console.log('append', data)
      this.dialogVisible = true
    },
    edit (data) {
      this.dialogType = 'edit'
      this.title = '修改分类'
      // 后台获取最新数据进行回显
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        this.category.name = data.data.name
        this.category.catId = data.data.catId
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
      })
      this.dialogVisible = true
    },
    submitData () {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else {
        this.editCategory()
      }
    },
    addCategory () {
      console.log(this.category)
      this.$refs['category'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/product/category/save'),
            method: 'post',
            data: this.$http.adornData(this.category, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '菜单保存成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.category.name = null
              // 刷新菜单
              this.getMenuList()
              // 设置节点父节点展开
              this.expandKey = [this.category.parentCid]
            } else {
              this.$message.error(data.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    editCategory () {
      var {name, catId, icon, productUnit} = this.category
      this.$refs['category'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/product/category/update'),
            method: 'post',
            data: this.$http.adornData({name, catId, icon, productUnit}, false)
          }).then(({data}) => {
            this.$message({
              message: '菜单修改成功',
              type: 'success'
            })
            // 关闭对话框
            this.dialogVisible = false
            // 刷新菜单
            this.getMenuList()
            // 设置节点父节点展开
            this.expandKey = [this.category.parentCid]
          })
        } else {
          return false
        }
      })
    },
    remove (node, data) {
      console.log('remove', node, data)
      var ids = [data.catId]
      this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '菜单删除成功',
              type: 'success'
            })
            // 刷新菜单
            this.getMenuList()
            // 设置删除节点父节点展开
            this.expandKey = [node.data.parentCid]
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    allowDrop (draggingNode, dropNode, type) {
      // 1、被拖动的当前节点以及所在父节点总层数 不能大于3层
      // console.log('allowDrop :', draggingNode, dropNode, type)
      // 当前正在拖动的节点+父节点所在的深度不大于3即可
      this.countNodeLevel(draggingNode.data)
      // console.log('当前节点最大深度：', this.maxLevel)
      // eslint-disable-next-line no-unused-vars
      let deep = this.maxLevel - draggingNode.level + 1
      if (type === 'inner') {
        return (deep + dropNode.level) <= 3
      } else {
        return (deep + dropNode.parent.level) <= 3
      }
    },
    handleDrop (draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', dropNode.label, dropType)
      let pCid = 0
      let siblings = null
      if (dropType === 'before' || dropType === 'after') {
        pCid = dropNode.parent.data.catId === undefined ? 0 : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      for (let i = 0; i < siblings.length; i++) {
        // 当前处理的节点是否是被拖拽的节点
        if (siblings[i].data.catId === draggingNode.data.catId) {
          // let catLevel = draggingNode.level
          // 如果当前拖拽的节点层级发生了变化则修改当前及子节点层级
          if (draggingNode.level !== siblings[i].level) {
            // catLevel = siblings[i].level
            this.updateChildNodeLevel(siblings[i])
          }
          // 如果遍历的正是当前拖拽节点的ID则需要更新当前节点的父ID
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid})
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
        }
      }
      console.log('updateNodes', this.updateNodes)
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({data}) => {
        this.$message({
          message: '菜单修改成功',
          type: 'success'
        })
        // 刷新菜单
        this.getMenuList()
        // 设置删除节点父节点展开
        this.expandKey = [pCid]
        this.updateNodes = []
        this.maxLevel = 0
      })
    },
    updateChildNodeLevel (node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          const cNode = node.childNodes[i].data
          this.updateNodes.push({catId: cNode.catId, catLevel: node.childNodes[i].level})
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    countNodeLevel (node) {
      // 找到所有子节点求出最大深度
      if (node.children != null && node.children.length > 0) {
        // 如果当前节点有子节点，则循环所有子节点找到最深的层级
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            // 如果当前节点层级比之前的更深则覆盖最深层级
            this.maxLevel = node.children[i].catLevel
          }
          this.countNodeLevel(node.children[i])
        }
      } else {
        this.maxLevel = node.catLevel
      }
    }

  },

  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getMenuList()
  },
  beforeCreate () {
  }, // 生命周期 - 创建之前
  beforeMount () {
  }, // 生命周期 - 挂载之前
  beforeUpdate () {
  }, // 生命周期 - 更新之前
  updated () {
  }, // 生命周期 - 更新之后
  beforeDestroy () {
  }, // 生命周期 - 销毁之前
  destroyed () {
  }, // 生命周期 - 销毁完成
  activated () {
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
</style>
